package com.lenovo.study.core.shiro;

import com.lenovo.study.dao.PermissionMapper;
import com.lenovo.study.dao.UserMapper;
import com.lenovo.study.model.Permission;
import com.lenovo.study.model.Role;
import com.lenovo.study.model.User;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Author: fuxh3@lenovo.com
 * Date: Created in 2017/8/31 0031
 */
public class ShiroRealm extends AuthorizingRealm {
    private static final Logger logger = LogManager.getLogger(ShiroRealm.class);
    @Autowired
    UserMapper userMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("doGetAuthorizationInfo+"+principalCollection.toString());
        User user = userMapper.getByUserName((String) principalCollection.getPrimaryPrincipal());
        SecurityUtils.getSubject().getSession().setAttribute(String.valueOf(user.getId()),SecurityUtils.getSubject().getPrincipals());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //赋予角色
        for(Role userRole:user.getRoles()){
            info.addRole(userRole.getName());
        }
        //赋予权限
        for(Permission permission:permissionMapper.getByUserId(user.getId())){
            info.addStringPermission(permission.getName());
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
                                    throws AuthenticationException {
        logger.info("doGetAuthenticationInfo+"+authenticationToken.toString());
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        User user = userMapper.getByUserName(username);
        if (user != null) {
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute("user", user);
            return new SimpleAuthenticationInfo(username,user.getPassword(),getName());
        } else {
            return null;
        }

    }
}
